using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using GrapeCity.Forguncy.Commands;
using GrapeCity.Forguncy.Plugin;
using iTextSharp.text.pdf;
using Spire.Pdf;
using PdfDocument = Spire.Pdf.PdfDocument;

namespace PdfOperationCommand
{
    [Icon("pack://application:,,,/PdfOperationCommand;component/Resources/Converter.png")]
    [OrderWeight(7)]
    [Description("转换 PDF 文件到其他格式，使用 Spire.Pdf 实现")]
    public class PdfConvertToServerCommand : BaseServerCommand, ICommandExecutableInServerSideAsync
    {
        [Required]
        [FormulaProperty]
        [DisplayName("文件路径")]
        [Description("文件绝对路径，如：D:\\example.pdf(Windows)，/path/example.pdf(Linux)")]
        public object FilePath { get; set; }

        [DisplayName("转换格式")]
        [Description("转换格式")]
        public PdfConvertFileType ConvertFileFormat { get; set; }

        [Required]
        [FormulaProperty]
        [DisplayName("输出文件路径")]
        [Description("文件绝对路径，如：D:\\example.pdf(Windows)，/path/example.pdf(Linux)")]
        public object OutFilePath { get; set; }

        public async Task<ExecuteResult> ExecuteAsync(IServerCommandExecuteContext dataContext)
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            var filePath = await GetParamValue(dataContext, FilePath);
            var outFilePath = await GetParamValue(dataContext, OutFilePath);
            PdfDocument pdf = new PdfDocument();
            pdf.LoadFromFile(filePath.ToString());
            switch (ConvertFileFormat)
            {
                case PdfConvertFileType.PPTX:
                    pdf.SaveToFile(outFilePath.ToString(), FileFormat.PPTX);
                    pdf.Close();
                    break;
                case PdfConvertFileType.OFD:
                    pdf.SaveToFile(outFilePath.ToString(), FileFormat.OFD);
                    pdf.Close();
                    break;
                case PdfConvertFileType.XLSX:
                    pdf.SaveToFile(outFilePath.ToString(), FileFormat.XLSX);
                    pdf.Close();
                    break;
                default:
                    pdf.Close();
                    throw new ArgumentOutOfRangeException();
            }
            return new ExecuteResult();
        }

        public override string ToString()
        {
            return "转换 PDF 文件到其他格式";
        }
    }

    public enum PdfConvertFileType
    {
        [Description("PPTX")] PPTX,
        [Description("OFD")] OFD,
        [Description("XLSX")] XLSX,
    }
}